package cn.edu.nchu.comic_strip.ui.bookmark;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.edu.nchu.comic_strip.App;
import cn.edu.nchu.comic_strip.R;
import cn.edu.nchu.comic_strip.database.dao.BookDao;
import cn.edu.nchu.comic_strip.database.dao.PageDao;
import cn.edu.nchu.comic_strip.databinding.FragmentBookmarkBinding;
import cn.edu.nchu.comic_strip.entity.Book;
import cn.edu.nchu.comic_strip.entity.Page;
import cn.edu.nchu.comic_strip.model.BookMarkBook;
import cn.edu.nchu.comic_strip.model.CollectionBook;
import cn.edu.nchu.comic_strip.ui.collection.CollectionBookListAdapter;


public class BookmarkFragment extends Fragment {

    private FragmentBookmarkBinding binding;
    private Context mContext;
    private List<Page> pagesList;
    private ListView listView;
    private BookMarkBookListAdapter adapter;

    private PageDao pageDao = App.getAppDatabase().getPageDao();
    private BookDao bookDao = App.getAppDatabase().getBookDao();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        BookmarkViewModel notificationsViewModel =
                new ViewModelProvider(this).get(BookmarkViewModel.class);

        binding = FragmentBookmarkBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化 mContext
        mContext = getContext();

        // 获取页码列表
        pagesList= pageDao.getBookMark();

        // 过滤并分组页面
        Map<Integer, List<Page>> pagesGroupedByBook = pagesList.stream()
                .filter(page -> page.getIsBookmark() == 1)
                .collect(Collectors.groupingBy(Page::getBookId));

        // 创建书籍集合
        List<BookMarkBook> bookMarkBooks = new ArrayList<>();
        for (Map.Entry<Integer, List<Page>> entry : pagesGroupedByBook.entrySet()) {
            int bookId = entry.getKey();
            List<Page> bookMarkPages = entry.getValue();
            int collectionCount = bookMarkPages.size();

            Book book = bookDao.getBook(bookId);
            if (book != null) {
                BookMarkBook bookMarkBook = new BookMarkBook(
                        book.getId(),
                        book.getBookName(),
                        book.getBookCover(),
                        collectionCount
                );
                bookMarkBooks.add(bookMarkBook);
            }
        }

        if (bookMarkBooks.isEmpty()) {
            // 显示没有收藏的书籍提示页面
            root = inflater.inflate(R.layout.fragment_no_book_mark, container, false);
        } else {
            // 设置书籍总数
            TextView bookCountTextView = root.findViewById(R.id.book_mark_book_count_text);
            bookCountTextView.setText("共" + bookMarkBooks.size() + "本书");

            // 设置列表视图和适配器
            listView = root.findViewById(R.id.collection_book_list);
            adapter = new BookMarkBookListAdapter(mContext, bookMarkBooks);
            listView.setAdapter(adapter);

            // Set click event
            listView.setOnItemClickListener((adapterView, view, position, id) -> {
                List<Page> bookmarkedPages = pagesGroupedByBook.get(id);
                Intent intent = new Intent("cn.edu.nchu.comic_strip.ui.bookmark.BookMarkBookDetailActivity");
                intent.putExtra("bookId", bookMarkBooks.get(position).getId());  // Pass bookId
                startActivity(intent);  // Start Activity
            });
        }

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}